package com.achen.mall.product.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.achen.common.utils.PageUtils;
import com.achen.common.utils.Query;

import com.achen.mall.product.dao.CategoryDao;
import com.achen.mall.product.entity.CategoryEntity;
import com.achen.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

//    @Autowired
//    private CategoryDao categoryDao; //也可以使用baseMapper，因为继承了ServiceImpl，里面已经注入了baseMapper，所以可以直接用baseMapper

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    //树形结构展示所有分类
    public List<CategoryEntity> findCategoryWithTree() {
        //查出所有分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        //树形结构展示数据
        //1.找到所有的一级分类
        List<CategoryEntity> level1List = categoryEntityList.stream().
                filter(categoryEntity -> categoryEntity.getParentCid() == 0).
                map(menu -> {
                    menu.setChildren(getChildren(menu,categoryEntityList));
                    return menu;
                }).
                sorted((menu1,menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).
                collect(Collectors.toList());
        return level1List;
    }

    @Override
    public void deleteMenuByIds(List<Long> catIds) {
        //检查当前目录是不是可以被直接删除
        //TODO baseMapper.deleteBatchIds(catIds);
        baseMapper.deleteBatchIds(catIds);
    }

    //rootMenu 当前菜单 all 所有菜单
    public List<CategoryEntity> getChildren(CategoryEntity rootMenu,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == rootMenu.getCatId();
        }).map(categoryEntity -> {
            //找到子菜单
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}